$(function(){
	var $products = [];
	var $storehouses = [];
	var $storehouse_types = [
		{ id: 'MAIN', text: '中心库房'},
		{ id: 'SUB', text: '分站库房' }
	];
	var convert = function(storehouse){
		return [
			storehouse.id,
			storehouse.name,
			storehouse.address,
			storehouse.manager,
			function(type){
				for (var i = 0; i < $storehouse_types.length; ++i) {
					if ($storehouse_types[i].id === type) {
						return $storehouse_types[i];
					}
				}
			}(storehouse.type),
			null
		];
	};
	$('.refresh-link').click(function() {
		$.get('../api/products.json').done(function(response){
			$products = response.data.sort(function(a, b){ return a.id - b.id; });
			$.each($products, function(){
				this.text = this.name;
			});
			$('#record-product').empty().append('<option>').select2({ data: $products, allowClear: true });
		});
		$('#new').submit(function(){
			event.preventDefault();
			var form = this;
			$.post('../' + Feces.url.storehouse, $(this).serialize()).done(function(result){
				if (result.status === 0) {
					var storehouse = result.data;
					storehouse.text = storehouse.name;
					$('#display').dataTable().fnAddData(convert(storehouse));
					$storehouses.push(storehouse);
					$('#record-storehouse').trigger('change');
					$('#query-storehouse').trigger('change');
					form.reset();
					toastr.success('创建成功');
				} else {
					toastr.error('创建失败');
				}
			}).fail(function(){
				toastr.error('创建失败');
			});
		});
		$('#new-type').select2({ data: $storehouse_types });
		$('#display').dataTable({
			ajax: {
				url: '../' + Feces.url.storehouses + '.json',
				dataSrc: function(response){
					$storehouses = response.data.sort(function(a, b){ return a.id - b.id; });
					$.each($storehouses, function(){
						this.text = this.name;
					});
					$('#record-storehouse').empty().append('<option>').select2({ data: $storehouses, allowClear: true });
					$('#query-storehouse').empty().append('<option>').select2({ data: $storehouses, allowClear: true });
					return $storehouses.map(convert);
				}
			},
			stateSave: true,
			createdRow: function(row, data, dataIndex){
				$(row).data({ id: data[0] });
				$('td:eq(0)', row).data({ name: 'id' });
				$('td:eq(1)', row).data({
					name: 'name',
					type: 'text',
					title: '库房名',
					placeholder: '请输入库房名'
				}).attr('data-editable', true);
				$('td:eq(2)', row).data({
					name: 'address',
					type: 'text',
					title: '库房地址',
					placeholder: '请输入库房地址'
				}).attr('data-editable', true);
				$('td:eq(3)', row).data({
					name: 'manager',
					type: 'text',
					title: '库管员',
					placeholder: '请输入库管员'
				}).attr('data-editable', true);
				$('td:eq(4)', row).data({
					name: 'type',
					type: 'select2',
					title: '库房级别',
					value: data[4].id,
					source: $storehouse_types,
				}).attr('data-editable', true).text(data[4].text);
				$('td:eq(5)', row).append(
					$('<a>')
					.addClass('btn btn-circle btn-danger')
					.attr('href', 'javascript:void(0);')
					.attr('title', '删除库房')
					.html('<em class="fa fa-trash-o"></em>')
					.click(function(){
						var link = $(this);
						$.ajax({
							type: 'DELETE',
							url: '../' + Feces.url.storehouse + '.json',
							data: { id: link.closest('tr').data('id') }
						}).done(function(result){
							if (result.status === 0) {
								toastr.success('删除成功');
								link.closest('table').dataTable().fnDeleteRow(dataIndex);
							} else {
								toastr.error('删除失败: ' + result.message);
							}
						}).fail(function(){
							toastr.error('删除失败');
						});
					})
				);
				$('[data-editable=true]', row).each(function(){
					var cell = $(this);
					cell.wrapInner($('<a>')).children().editable($.extend({
						pk: $(this).closest('tr').data('id'),
						emptytext: '',
						ajaxOptions: { type: 'PUT' },
						url: '../' + Feces.url.storehouse + '.json',
						success: function(response, new_value){
							if (response.status !== 0) {
								return response.message;
							}
						},
						validate: function(value){
							if($.trim(value) === '') {
								return '不能为空';
							}
						}
					}, cell.data()));
				});
			},
			destroy: true
		});
		$('#record').submit(function(){
			event.preventDefault();
			$.get(
				'../' + Feces.url.store_records + '.json',
				$(this).serialize()
			).done(function(result){
				if (result.status === 0) {
					$('#record-results').dataTable({
						data: function(data){
							return data.map(function(record){
								return [
									record.id,
									function(type){
										switch(type) {
										case 'I':
											return '入库';
										case 'O':
											return '出库';
										}
									}(record.type),
									record.storehouse.name,
									record.product.name,
									record.amount,
									(record.task || {number: ''}).number,
									new Date(record.created).toLocaleString()
								];
							});
						}(result.data),
						stateSave: true,
						destroy: true
					});
					$('#record').trigger('reset');
				} else {
					toastr.error('查询失败');
				}
			}).fail(function(){
				toastr.error('查询失败');
			});
		});
		$('#query').submit(function(){
			event.preventDefault();
			$.get(
				'../' + Feces.url.storehouse_products + '.json',
				$(this).serialize()
			).done(function(result){
				if (result.status === 0) {
					$('#query-results').dataTable({
						data: function(data){
							return data.map(function(record){
								var storehouse = function(id){
									for (var i = 0; i < $storehouses.length; ++i) {
										if ($storehouses[i].id === id) {
											return $storehouses[i];
										}
									}
								}(record.storehouseId);
								var product = function(id){
									for (var i = 0; i < $products.length; ++i) {
										if ($products[i].id === id) {
											return $products[i];
										}
									}
								}(record.productId);
								return [
									storehouse.id,
									storehouse.name,
									product.id,
									product.name,
									record.quantity,
									record.critical,
									record.limit
								];
							});
						}(result.data),
						stateSave: true,
						createdRow: function(row, data, dataIndex){
							$(row).data({
								id: {
									storehouse_id: data[0],
									product_id: data[2]
								}
							});
							$('td:eq(5)', row).data({
								name: 'critical',
								type: 'number',
								title: '警戒库存',
								placeholder: '请输入警戒库存'
							}).attr('data-editable', true);
							$('td:eq(6)', row).data({
								name: 'limit',
								type: 'number',
								title: '最大库存',
								placeholder: '请输入最大库存'
							}).attr('data-editable', true);
							$('[data-editable=true]', row).each(function(){
								var cell = $(this);
								cell.wrapInner($('<a>')).children().editable($.extend({
									pk: $(this).closest('tr').data('id'),
									emptytext: '',
									ajaxOptions: { type: 'PUT' },
									url: '../' + Feces.url.storehouse_product + '.json',
									success: function(response, new_value){
										if (response.status !== 0) {
											return response.message;
										}
									},
									validate: function(value){
										if($.trim(value) === '') {
											return '不能为空';
										}
									}
								}, cell.data()));
							});
						},
						destroy: true
					});
					$('#query').trigger('reset');
				} else {
					toastr.error('查询失败');
				}
			}).fail(function(){
				toastr.error('查询失败');
			});
		});
		$('.input-daterange').datepicker({
			keyboardNavigation: false,
			forceParse: false,
			autoclose: true
		});
	}).click();
});